//
//  NotifyManager.swift
//  cangchu
//  通知管理
//  Created by kang on 2021/11/26.
//

import Foundation
import UIKit
import CoreData
import UserNotifications

public class NotifyManager:NSObject,UNUserNotificationCenterDelegate{
    
    public static let share = NotifyManager()
    
    public func notify(text:String){
        if PushConfig.isShowNotify{
            let notify = json2Model(Notify.self, json: text)
            
            sendNotify(notify: notify)
        }
    }
    
    /**
     通知注册
     */
    public func register(){
        if #available(iOS 10.0, *) {
            
            let center = UNUserNotificationCenter.current()
            center.delegate = self;
            center.requestAuthorization(options: (UNAuthorizationOptions(rawValue: UNAuthorizationOptions.RawValue(UInt8(UNAuthorizationOptions.badge.rawValue) | UInt8(UNAuthorizationOptions.alert.rawValue) | UInt8(UNAuthorizationOptions.sound.rawValue)))), completionHandler: { (granted, error) in
                
                if error != nil {
                    print("成功了")
                }
            })
            UIApplication.shared.registerForRemoteNotifications()
        } else {
            
            let settings = UIUserNotificationSettings.init(types: (UIUserNotificationType(rawValue: UIUserNotificationType.RawValue(UInt8(UIUserNotificationType.alert.rawValue) | UInt8(UIUserNotificationType.badge.rawValue) | UInt8(UIUserNotificationType.sound.rawValue)))), categories: nil)
            UIApplication.shared.registerUserNotificationSettings(settings)
            UIApplication.shared.registerForRemoteNotifications()
        }
    }
    
    public func sendNotify(notify:Notify){
        if #available(iOS 10.0, *) {
            
            // 1.设置触发条件
            let timeTrigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 0.5, repeats: false)
            // 2.创建通知内容
            let content = UNMutableNotificationContent.init()
            content.body = notify.title ??  "新消息"
            content.badge = NSNumber(value:(UIApplication.shared.applicationIconBadgeNumber + 1))
            content.sound = UNNotificationSound.default
            let detail = notify.content ?? ""
            let userInfo:Dictionary<String,String>=["detail":detail]
            content.userInfo = userInfo
            // 3.通知标识
            let requestIdentifier = NSString.init(format: "%lf", NSDate().timeIntervalSince1970)
            // 4.创建通知请求，将1，2，3添加到请求中
            let request = UNNotificationRequest(identifier: requestIdentifier as String, content: content, trigger: timeTrigger)
            UNUserNotificationCenter.current().add(request, withCompletionHandler: { (error) in
                
                if error == nil {
                    print("推送成功")
                }
            })
            
        } else {
            
            let notification = UILocalNotification.init()
            notification.alertBody = notify.title ?? "新消息"
            notification.applicationIconBadgeNumber = UIApplication.shared.applicationIconBadgeNumber + 1
            notification.soundName = UILocalNotificationDefaultSoundName
            let detail = notify.content ?? ""
            let userInfo:Dictionary<String,String>=["detail":detail]
            notification.userInfo = userInfo
            DispatchQueue.main.asyncAfter(wallDeadline: DispatchWallTime.now()+5.0) {
                UIApplication.shared.presentLocalNotificationNow(notification)
            }
        }
    }
    
    @available(iOS 10.0, *)
    public func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Swift.Void) {
        
        completionHandler(UNNotificationPresentationOptions(rawValue: UNNotificationPresentationOptions.RawValue(UInt8(UNNotificationPresentationOptions.badge.rawValue) | UInt8(UNNotificationPresentationOptions.alert.rawValue) | UInt8(UNNotificationPresentationOptions.sound.rawValue))))
    }
    
    @available(iOS 10.0, *)
    public func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        completionHandler()
    }
}
